package com.umeox.moto.watch.fitness.utils;

import android.os.AsyncTask;
import android.os.Environment;

import com.umeox.moto.common.utils.DateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * Created by zl on 2018/7/14.
 */

public class LogUtils {

    public static void saveLog( String content) {


       final String message =  DateUtils.formatDateTime(System.currentTimeMillis())+" "+content;
        AsyncTask.execute(() -> {
            //创建一个带缓冲区的输出流
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                String logPath = sdPath + "/Dev/Fitness/log/";
                File file = new File(logPath);
                FileOutputStream fos = null;
                OutputStreamWriter writer = null;
                try {
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    File logFile = new File(file,"fitness_log.txt");
                    fos = new FileOutputStream(logFile,true);
                    writer = new OutputStreamWriter(fos, "utf-8");
                    writer.write(message);
                    writer.write("\n");

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (writer != null) {
                            writer.close();
                        }

                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

}
